
declare @schema nvarchar(50)
		,@tabla nvarchar(50)
		,@name nvarchar(100)
		,@percent float
		,@qry nvarchar(max)
declare qIndices cursor for
	select sch.name,ob.name,ind.name,sy.avg_fragmentation_in_percent
		from sys.dm_db_index_physical_stats(db_id('AdventureWorks2012'),null,null,null,'detailed') sy
			join sys.indexes ind on sy.object_id=ind.object_id
			join sys.objects ob on sy.object_id=ob.object_id
			join sys.schemas sch on ob.schema_id=sch.schema_id  
		where avg_fragmentation_in_percent>1 and ind.name like 'IX%'
open qIndices
FETCH NEXT FROM qIndices INTO @schema,@tabla,@name,@percent
While @@FETCH_STATUS = 0
begin
	set @qry = N'Alter Index '+@name + ' on ' +QUOTENAME(@schema)+'.'+QUOTENAME(@tabla)
	if(@percent <= 30)
		begin
			set @qry += N' reorganize'
		end
	else
		begin
			set @qry += N' rebuild'
		end
	print @qry
	--set @qry=N''
	FETCH NEXT FROM qIndices INTO @schema,@tabla,@name,@percent
END
CLOSE qIndices
DEALLOCATE qIndices
